<template>
  <div class="user-management">
    <div class="header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <button @click="showAddDialog = true" class="btn btn-primary">
          <i class="fas fa-plus"></i> 新增用户
        </button>
      </div>
    </div>

    <!-- 搜索过滤区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>关键词搜索:</label>
          <input
            v-model="searchParams.keyword"
            type="text"
            placeholder="用户名或姓名"
            class="form-input"
            @keyup.enter="loadUserList"
          />
        </div>
        <div class="filter-item">
          <label>用户类型:</label>
          <select v-model="searchParams.userType" class="form-select">
            <option value="">全部类型</option>
            <option value="admin">管理员</option>
            <option value="user">普通用户</option>
            <option value="ban">已封禁</option>
          </select>
        </div>
        <div class="filter-item">
          <label>状态:</label>
          <select v-model="searchParams.enabled" class="form-select">
            <option value="">全部状态</option>
            <option value="1">启用</option>
            <option value="0">禁用</option>
          </select>
        </div>
        <div class="filter-actions">
          <button @click="loadUserList" class="btn btn-info">
            <i class="fas fa-search"></i> 搜索
          </button>
          <button @click="resetSearch" class="btn btn-secondary">
            <i class="fas fa-redo"></i> 重置
          </button>
        </div>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>头像</th>
            <th>用户信息</th>
            <th>联系方式</th>
            <th>用户类型</th>
            <th>会员等级</th>
            <th>消费信息</th>
            <th>状态</th>
            <th>最后登录</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in userList" :key="user.id">
            <td>{{ user.id }}</td>
            <td class="user-avatar">
              <img v-if="user.avatar" :src="user.avatar" :alt="user.name" class="avatar-image" />
              <div v-else class="avatar-placeholder">
                <i class="fas fa-user"></i>
              </div>
            </td>
            <td class="user-info">
              <div class="user-details">
                <strong>{{ user.name || user.username }}</strong>
                <div class="user-meta">
                  <span class="username">@{{ user.username }}</span>
                  <span v-if="user.sex" class="gender">
                    {{ user.sex === 1 ? '男' : user.sex === 2 ? '女' : '未知' }}
                  </span>
                </div>
              </div>
            </td>
            <td class="contact-info">
              <div v-if="user.phone" class="contact-item">
                <i class="fas fa-phone"></i> {{ user.phone }}
              </div>
              <div v-if="user.email" class="contact-item">
                <i class="fas fa-envelope"></i> {{ user.email }}
              </div>
            </td>
            <td>
              <span :class="['user-type-badge', `type-${user.userType}`]">
                {{ getUserTypeText(user.userType || 'user') }}
              </span>
            </td>
            <td>
              <span :class="['member-level-badge', `level-${user.memberLevel}`]">
                {{ getMemberLevelText(user.memberLevel || 2) }}
              </span>
            </td>
            <td class="spend-info">
              <div class="spend-item">
                <span class="spend-label">累计:</span>
                <span class="spend-value">¥{{ formatMoney(user.totalSpent || 0) }}</span>
              </div>
              <div class="spend-item">
                <span class="spend-label">今年:</span>
                <span class="spend-value">¥{{ formatMoney(user.currentYearSpent || 0) }}</span>
              </div>
              <div class="spend-item">
                <span class="spend-label">订单:</span>
                <span class="spend-value">{{ user.orderCount }}单</span>
              </div>
            </td>
            <td>
              <span :class="['status-badge', user.enabled === 1 ? 'status-active' : 'status-inactive']">
                {{ user.enabled === 1 ? '启用' : '禁用' }}
              </span>
            </td>
            <td>
              <div v-if="user.lastLoginTime">
                {{ formatDateTime(user.lastLoginTime) }}
                <div class="login-count">登录{{ user.loginTimes }}次</div>
              </div>
              <span v-else class="no-login">未登录</span>
            </td>
            <td class="actions">
              <button @click="editUser(user)" class="btn btn-sm btn-warning">
                <i class="fas fa-edit"></i> 编辑
              </button>
              <button 
                @click="toggleUserStatus(user)" 
                :class="['btn', 'btn-sm', user.enabled === 1 ? 'btn-danger' : 'btn-success']"
              >
                <i :class="user.enabled === 1 ? 'fas fa-ban' : 'fas fa-check'"></i>
                {{ user.enabled === 1 ? '禁用' : '启用' }}
              </button>
            </td>
          </tr>
          <tr v-if="userList.length === 0">
            <td colspan="10" class="no-data">暂无用户数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-section">
      <div class="pagination-info">
        共 {{ total }} 条记录，第 {{ current }} / {{ Math.ceil(total / pageSize) }} 页
      </div>
      <div class="pagination-controls">
        <button
          @click="changePage(current - 1)"
          :disabled="current <= 1"
          class="btn btn-sm btn-secondary"
        >
          上一页
        </button>
        <span class="page-numbers">
          <button
            v-for="page in getPageNumbers()"
            :key="page"
            @click="changePage(page)"
            :class="['btn', 'btn-sm', page === current ? 'btn-primary' : 'btn-outline']"
          >
            {{ page }}
          </button>
        </span>
        <button
          @click="changePage(current + 1)"
          :disabled="current >= Math.ceil(total / pageSize)"
          class="btn btn-sm btn-secondary"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 新增/编辑用户弹窗 -->
    <div v-if="showAddDialog || showEditDialog" class="modal-overlay">
      <div class="modal-content user-form-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditDialog ? '编辑用户' : '新增用户' }}</h3>
          <button @click="closeDialog" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUser">
            <div class="form-row">
              <div class="form-group">
                <label>用户名 *</label>
                <input v-model="formData.username" type="text" required class="form-input" placeholder="请输入用户名" />
              </div>
              <div class="form-group">
                <label>姓名</label>
                <input v-model="formData.name" type="text" class="form-input" placeholder="请输入真实姓名" />
              </div>
            </div>
            
            <!-- 新增用户时显示密码字段 -->
            <div v-if="showAddDialog" class="form-row">
              <div class="form-group">
                <label>密码 *</label>
                <input v-model="formData.password" type="password" required class="form-input" placeholder="请输入密码（至少8位）" />
              </div>
              <div class="form-group">
                <label>确认密码 *</label>
                <input v-model="formData.checkPassword" type="password" required class="form-input" placeholder="请再次输入密码" />
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label>手机号</label>
                <input v-model="formData.phone" type="tel" class="form-input" placeholder="请输入手机号" />
              </div>
              <div class="form-group">
                <label>邮箱</label>
                <input v-model="formData.email" type="email" class="form-input" placeholder="请输入邮箱" />
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label>性别</label>
                <select v-model.number="formData.sex" class="form-select">
                  <option :value="0">未知</option>
                  <option :value="1">男</option>
                  <option :value="2">女</option>
                </select>
              </div>
              <div class="form-group">
                <label>生日</label>
                <input v-model="formData.birthday" type="date" class="form-input" />
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label>用户类型</label>
                <select v-model="formData.userType" class="form-select">
                  <option value="user">普通用户</option>
                  <option value="admin">管理员</option>
                  <option value="ban">已封禁</option>
                </select>
              </div>
              <div class="form-group">
                <label>会员等级</label>
                <select v-model.number="formData.memberLevel" class="form-select">
                  <option :value="2">普通会员</option>
                  <option :value="1">白金会员</option>
                  <option :value="0">黑金会员</option>
                </select>
              </div>
            </div>
            
            <div class="form-group">
              <label>头像链接</label>
              <input v-model="formData.avatar" type="url" class="form-input" placeholder="请输入头像图片链接" />
            </div>
            
            <div class="form-group">
              <label>状态</label>
              <select v-model.number="formData.enabled" class="form-select">
                <option :value="1">启用</option>
                <option :value="0">禁用</option>
              </select>
            </div>
            
            <div class="form-actions">
              <button type="button" @click="closeDialog" class="btn btn-secondary">取消</button>
              <button type="submit" :disabled="saving" class="btn btn-primary">
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { listUserVOByPage, updateUser, userRegister } from '@/api/user'
import type { UserVO, UserQueryRequest, UserUpdateRequest, UserRegisterRequest } from '@/types/user'

// 响应式数据
const userList = ref<UserVO[]>([])
const total = ref(0)
const current = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const saving = ref(false)

// 弹窗状态
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const currentUser = ref<UserVO | null>(null)

// 搜索参数
const searchParams = reactive<UserQueryRequest>({
  current: 1,
  pageSize: 10,
  keyword: '',
  userType: '',
  enabled: undefined
})

// 表单数据
const formData = reactive({
  id: 0,
  username: '',
  name: '',
  avatar: '',
  sex: 0,
  birthday: '',
  phone: '',
  email: '',
  userType: 'user',     // 使用驼峰命名与后端一致
  memberLevel: 2,       // 使用驼峰命名与后端一致
  enabled: 1,
  password: '',         // 新增用户时使用
  checkPassword: ''     // 新增用户时使用
})

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    searchParams.current = current.value
    searchParams.pageSize = pageSize.value
    const response = await listUserVOByPage(searchParams)
    userList.value = response.data.records
    total.value = response.data.total
    
    // 自动检查并更新会员等级
    await autoUpdateMemberLevels()
  } catch (error) {
    console.error('加载用户列表失败:', error)
    alert('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = ''
  searchParams.userType = ''
  searchParams.enabled = undefined
  current.value = 1
  loadUserList()
}

// 分页切换
const changePage = (page: number) => {
  if (page < 1 || page > Math.ceil(total.value / pageSize.value)) return
  current.value = page
  loadUserList()
}

// 获取分页数字
const getPageNumbers = () => {
  const nums: number[] = []
  const totalPages = Math.ceil(total.value / pageSize.value)
  const start = Math.max(1, current.value - 2)
  const end = Math.min(totalPages, current.value + 2)
  
  for (let i = start; i <= end; i++) {
    nums.push(i)
  }
  return nums
}

// 编辑用户
const editUser = (user: UserVO) => {
  currentUser.value = user
      Object.assign(formData, {
      id: user.id,
      username: user.username,
      name: user.name || '',
      avatar: user.avatar || '',
      sex: user.sex || 0,
      birthday: user.birthday ? user.birthday.split('T')[0] : '',
      phone: user.phone || '',
      email: user.email || '',
      userType: user.userType || 'user',
      memberLevel: user.memberLevel || 2,
      enabled: user.enabled || 1
    })
  showEditDialog.value = true
}

// 切换用户状态
const toggleUserStatus = async (user: UserVO) => {
  const newStatus = user.enabled === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '禁用'
  
  if (!confirm(`确定要${action}用户"${user.username}"吗？`)) return
  
  try {
    const updateData: UserUpdateRequest = {
      id: user.id,
      enabled: newStatus
    }
    await updateUser(updateData)
    alert(`${action}成功`)
    loadUserList()
  } catch (error) {
    console.error(`${action}用户失败:`, error)
    alert(`${action}用户失败`)
  }
}

// 保存用户
const saveUser = async () => {
  saving.value = true
  try {
    if (showEditDialog.value && currentUser.value) {
      // 编辑模式：更新现有用户
    const userData: UserUpdateRequest = {
      id: formData.id,
      username: formData.username,
      name: formData.name,
      avatar: formData.avatar,
      sex: formData.sex,
        birthday: formData.birthday ? formData.birthday + 'T00:00:00' : '',
      phone: formData.phone,
      email: formData.email,
      userType: formData.userType,     // 使用驼峰命名
      memberLevel: formData.memberLevel,   // 使用驼峰命名
      enabled: formData.enabled
    }
      await updateUser(userData)
      alert('更新成功')
    } else {
      // 新增模式：创建新用户
      // 验证输入
      if (!formData.username || formData.username.length < 4) {
        alert('用户名长度不能少于4位')
        return
      }
      
      if (formData.password !== formData.checkPassword) {
        alert('两次输入的密码不一致')
        return
      }
      
      if (formData.password.length < 8) {
        alert('密码长度不能少于8位')
        return
      }
      
      // 注册新用户
      const registerData: UserRegisterRequest = {
        username: formData.username,
        password: formData.password,
        checkPassword: formData.checkPassword
      }
      
      const newUserId = await userRegister(registerData)
      
      // 如果有其他信息需要更新，可以调用更新API
      if (formData.name || formData.avatar || formData.phone || formData.email || 
          formData.sex !== 0 || formData.birthday || formData.userType !== 'user' || 
          formData.memberLevel !== 2 || formData.enabled !== 1) {
        
        const updateData: UserUpdateRequest = {
          id: newUserId.data,
          username: formData.username,
          name: formData.name,
          avatar: formData.avatar,
          sex: formData.sex,
          birthday: formData.birthday ? formData.birthday + 'T00:00:00' : '',
          phone: formData.phone,
          email: formData.email,
          userType: formData.userType,
          memberLevel: formData.memberLevel,
          enabled: formData.enabled
        }
        
        await updateUser(updateData)
      }
      
      alert('新增用户成功')
    }
    
    closeDialog()
    loadUserList()
  } catch (error: any) {
    console.error('保存用户失败:', error)
    const errorMessage = error?.response?.data?.message || error?.message || '未知错误'
    alert(`保存用户失败: ${errorMessage}`)
  } finally {
    saving.value = false
  }
}

// 关闭弹窗
const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  currentUser.value = null
  Object.assign(formData, {
    id: 0,
    username: '',
    name: '',
    avatar: '',
    sex: 0,
    birthday: '',
    phone: '',
    email: '',
    userType: 'user',
    memberLevel: 2,
    enabled: 1,
    password: '',
    checkPassword: ''
  })
}

// 获取用户类型文本
const getUserTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'admin': '管理员',
    'user': '普通用户',
    'ban': '已封禁'
  }
  return typeMap[type] || '未知'
}

// 获取会员等级文本
const getMemberLevelText = (level: number) => {
  const levelMap: Record<number, string> = {
    0: '黑金会员',
    1: '白金会员',
    2: '普通会员'
  }
  return levelMap[level] || '未知'
}

// 根据消费金额计算实际会员等级
const getActualMemberLevel = (user: UserVO): number => {
  const totalSpent = user.totalSpent || 0
  
  if (totalSpent >= 50000) {
    return 0 // 黑金会员
  } else if (totalSpent >= 10000) {
    return 1 // 白金会员
  } else {
    return 2 // 普通会员
  }
}



// 格式化金额
const formatMoney = (amount: number) => {
  return (amount || 0).toFixed(2)
}

// 自动更新会员等级（静默执行）
const autoUpdateMemberLevels = async () => {
  const usersToUpdate = userList.value.filter(user => {
    const actualLevel = getActualMemberLevel(user)
    return actualLevel !== user.memberLevel
  })
  
  if (usersToUpdate.length === 0) {
    return // 没有需要更新的用户，静默返回
  }
  
  console.log(`自动更新 ${usersToUpdate.length} 个用户的会员等级`)
  
  try {
    for (const user of usersToUpdate) {
      const actualLevel = getActualMemberLevel(user)
      await updateUser({
        id: user.id,
        username: user.username,
        name: user.name || '',
        avatar: user.avatar || '',
        sex: user.sex || 0,
        birthday: user.birthday || '',
        phone: user.phone || '',
        email: user.email || '',
        userType: user.userType || 'user',
        memberLevel: actualLevel,
        enabled: user.enabled || 1
      })
      
      user.memberLevel = actualLevel
    }
    
    console.log('自动更新会员等级完成')
  } catch (error) {
    console.error('自动更新会员等级失败:', error)
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  loadUserList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.filter-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.filter-item label {
  font-weight: 500;
  color: #555;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.form-input, .form-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  width: 200px;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,.25);
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th {
  background: #f8f9fa;
  padding: 12px 8px;
  text-align: left;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
}

.data-table td {
  padding: 12px 8px;
  border-bottom: 1px solid #dee2e6;
  vertical-align: middle;
}

.user-avatar {
  text-align: center;
}

.avatar-image {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e9ecef;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6c757d;
  margin: 0 auto;
}

.user-info .user-details strong {
  display: block;
  color: #333;
  margin-bottom: 2px;
}

.user-meta {
  display: flex;
  gap: 10px;
  font-size: 12px;
  color: #666;
}

.username {
  color: #007bff;
}

.contact-info .contact-item {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 3px;
  font-size: 12px;
  color: #666;
}

.user-type-badge, .member-level-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
}

.type-admin {
  background: #dc3545;
  color: white;
}

.type-user {
  background: #28a745;
  color: white;
}

.type-ban {
  background: #6c757d;
  color: white;
}

.level-0 {
  background: #212529;
  color: #ffd700;
}

.level-1 {
  background: #e9ecef;
  color: #495057;
}

.level-2 {
  background: #f8d7da;
  color: #721c24;
}



.spend-info .spend-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2px;
  font-size: 12px;
}

.spend-label {
  color: #666;
}

.spend-value {
  font-weight: 500;
  color: #333;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background: #d4edda;
  color: #155724;
}

.status-inactive {
  background: #f8d7da;
  color: #721c24;
}

.login-count {
  font-size: 11px;
  color: #666;
  margin-top: 2px;
}

.no-login {
  color: #999;
  font-style: italic;
}

.actions {
  white-space: nowrap;
}

.actions .btn {
  margin-right: 5px;
  margin-bottom: 5px;
}

.no-data {
  text-align: center;
  color: #666;
  font-style: italic;
  padding: 40px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-info {
  color: #666;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

.btn {
  padding: 8px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-outline {
  background: transparent;
  border: 1px solid #ddd;
  color: #333;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 11px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.user-form-modal {
  width: 90%;
  max-width: 800px;
}

.modal-content {
  background: #ffffff;
  border-radius: 4px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #999999;
  padding: 4px;
  line-height: 1;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #666666;
}

.modal-body {
  padding: 20px;
  background: #ffffff;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 18px;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  font-weight: 400;
  color: #666666;
  font-size: 14px;
}

.form-row .form-input,
.form-row .form-select {
  width: 100%;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}
</style> 